/**
 * 获取基础路劲
 *
 * @returns {string}
 */
const fs = require("fs");
const { app } = require('electron')
const {existsSync, readFileSync, unlinkSync} = require("fs");

// 存储基本路径
const getBaseDir = () => {
    let path = app.getPath('home') + '/.notes'
    if(!fs.existsSync(path)) {
        fs.mkdir(path)
    }
    return path;
}

// 文件是否存在
const isExists = (name) => {
    let path = getBaseDir() + '/' + name;
    return fs.existsSync(path)
}

// 获取完整文件路径
const getFullName = (name) => {
    return getBaseDir() + '/' + name
}

// 保存文件
const saveFile = (name, content) => {
    // console.log("当前操作文件", name)
    // fs.open(getFullName(name), 'w+', (err, fd)=>{
    //     fs.write(fd, content, (writeErr, written, string)=>{
    //         if(writeErr) throw writeErr;
    //     })
    // })
    // console.log("当前文件写入操作", name, getFullName(name), content)
    fs.writeFile(getFullName(name), content, (err)=>{
        // console.log("写入文件出错", err)
    })
}

// 删除指定文件
const deleteFile = (name) => {
    let filePath = getFullName(name)
    if(isExists(name)) {
        fs.unlinkSync(filePath);
    }
}

/**
 * 读取指定文件内容
 *
 * @param name
 * @param callback   (err, data)
 */
const readFile = (name, callback) =>  {
    console.log("文件路径", getFullName(name))
    fs.readFile(getFullName(name), callback)
}

/**
 * 读取文件成字符串
 *
 * @param name
 * @param callback
 */
const readFileAsString = (name) => {
    try {
        const data = fs.readFileSync(getFullName(name))
        const textDecoder = new TextDecoder('utf-8');
        return textDecoder.decode(data)
    } catch (e) {
        return null;
    }
}

// 读取所有文件
const readAllFile = () => {

}

module.exports = {
    getBaseDir,
    isExists,
    saveFile,
    readAllFile,
    readFile,
    readFileAsString,
    deleteFile,
}
